//
// Created by LiuYou on 2021/8/4.
//

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>


#define MEM_SIZE        1024


int main() {
    int shmId = shmget(IPC_PRIVATE, MEM_SIZE, 0600 );
    if (shmId < 0) {
        perror( "shmget()" );
        exit( 1 );
    }

    pid_t pid = fork();
    if (pid < 0) {
        perror( "fork()" );
        exit( 1 );
    }
    if (pid == 0) {
        void* ptr = shmat( shmId, nullptr, 0 );
        if (ptr == (void*) -1) {
            perror( "shmat()" );
            exit( 1 );
        }
        char* string = static_cast<char*>(ptr);
        strcpy( string, "Hello!" );
        shmdt( ptr );
        exit( 0 );
    } else {
        wait( nullptr );
        void* ptr = shmat( shmId, nullptr, 0 );
        if (ptr == (void*) -1) {
            perror( "shmat()" );
            exit( 1 );
        }
        char* string = static_cast<char*>(ptr);
        puts( string );
        shmdt( ptr );
        shmctl( shmId, IPC_RMID, nullptr );
        exit( 0 );
    }


}